package com.summer.safe.quartz.utils;

import com.summer.safe.quartz.dao.QuartzLogDao;
import com.summer.safe.quartz.entity.QuartzJob;
import com.summer.safe.quartz.entity.QuartzLog;
import com.summer.safe.quartz.service.QuartzLogService;
import com.summer.safe.utils.Exceptions;
import com.summer.safe.utils.Global;
import com.summer.safe.utils.SpringContextUtil;
import com.summer.safe.utils.StringUtils;
import org.springframework.core.NamedThreadLocal;

public class QuartzLogUtils {


    private static QuartzLogDao quartzLogDao = SpringContextUtil.getBean(QuartzLogDao.class);
    private static QuartzLogService quartzLogService = SpringContextUtil.getBean(QuartzLogService.class);
    //线程
    private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ThreadLocal StartTime");


    /**
     * 开始
     *
     */
    public static void start() {
        //开始时间
        long beginTime = System.currentTimeMillis();
        //线程绑定变量（该数据只有当前请求的线程可见）
        startTimeThreadLocal.set(beginTime);
    }
    /**
     * 任务日志
     */
    public static void end(QuartzJob quartzJob, Exception e) {
        //得到线程绑定的局部变量（开始时间）
        long beginTime = startTimeThreadLocal.get();
        //startTimeThreadLocal.remove();
        /*Date startTime = threadLocal.get();
        threadLocal.remove();*/
         QuartzLog quartzLog = new QuartzLog();
        quartzLog.setId(StringUtils.getUuid());
        quartzLog.setQuartzJob(quartzJob);
         //任务名称
        quartzLog.setJobName(quartzJob.getJobName());
        //任务组名
        quartzLog.setJobGroup(quartzJob.getJobGroup());
        //任务执行时调用的类

        quartzLog.setBeanClass(quartzJob.getBeanClass());
        //类的方法
        quartzLog.setMethodName(quartzJob.getMethodName());
        //参数
        quartzLog.setParams(quartzJob.getParams());
        //耗时
        quartzLog.setTime( String.valueOf(beginTime - System.currentTimeMillis()) );
       if (e != null) {
            quartzLog.setStatus(Global.FAIL);
           quartzLog.setExceptionInfo(Exceptions.getStackTraceAsString(e));
        }
        else {
           quartzLog.setStatus(Global.SUCCESS);
        }
        quartzLogDao.insert(quartzLog);
       // quartzLogService.save(quartzLog);

    }
}
